/************************************************************
 * Project Name         [Thinking_In_Java]
 * File Name            [Example_03_ThreadLocal.java]
 * Creation Date        [03-Jul-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ************************************************************/
package pkg_08_thread;

import java.text.SimpleDateFormat;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class Example_03_ThreadLocal {

	// 为每一个线程构建一个SimpleDateFormat的实例
	public static final ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM-dd");
		}
	};

	// 为每一个线程构建一个随机数生成器
	public static final ThreadLocal<Random> random = new ThreadLocal<Random>() {
		@Override
		protected Random initialValue() {
			return new Random();
		};
	};

	/**
	 * 测试方法
	 * 
	 * @param args
	 *            命令行参数
	 */
	public static void main(String[] args) {
		String date = dateFormat.get().format(new java.util.Date());
		System.out.println(date);

		int number = random.get().nextInt(10);
		System.out.println(number);

		// JDK7
		number = ThreadLocalRandom.current().nextInt(10);
		System.out.println(number);

	}

}
